<?php


namespace App\Http\Middleware;

use Closure;
use App\Jobs\Log\LogAddJob;
use App\Jobs\Message\Notice\RobotNewsJob;

class LogsMiddleware

{

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $path = $request->path();
        $method = strtolower($request->method()); // 转小写
        $arr = ['all', 'list', 'info', 'detail', 'batch', 'count', 'captcha']; // 排除路由 path中包含数组字符串的都将被排除

        // 去除查询请求 不做记录
        if ($method != 'get' && !count(array_intersect($arr, explode('/', $path)))) {

            $res = json_decode($response->getContent());
            $req = $request->all();
            $obj_id = @$req['guid'] ?: @$res->data->guid;
            $ip = $request->getClientIp();
            $url = $request->server('APP_URL');
            $user_id = $request->header('App-User') ?? '0';

            dispatch(new LogAddJob([
                'app_id' => $request->header('App-Platform') ?? '0',
                'user_id' => $user_id,
                'path' => $path,
                'method' => $method,
                'ip' => $ip,
                'request' => $req,
                'response' => $res,
                'url' => $url,
                'obj_id' => $obj_id,
                'log_time' => time()
            ]));

            // 发送异常通知
            if (@$res->code != 20000 && env('WX_WORK_ENABLED')) {
                $date = date('Y-m-d H:i:s');
                $res = json_encode($res, JSON_UNESCAPED_UNICODE);
                $req = json_encode($req, JSON_UNESCAPED_UNICODE);

                dispatch(new RobotNewsJob(array(
                    "text" => "=========接口错误========
                        > 请求域名: <font color='info'> {$url}</font>
                        > 请求IP: <font color='info'> {$ip}</font>
                        > 请求地址: <font color='info'> {$path}</font>
                        > 用户ID: <font color='info'> {$user_id}</font>
                        > 请求参数: <font color='warning'> {$req}</font>
                        > 处理结果: `{$res}`
                        > 服务器时间: <font color='info'> {$date}</font>"
                )));
            }
        }

        return $response;
    }
}
